package com.example.chat.controller;

import javax.servlet.http.HttpSession;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.chat.vo.R;
import com.example.chat.vo.ResultMessage;
import com.example.chat.vo.User;

import lombok.extern.slf4j.Slf4j;

/**
 * @author Lay.He
 * @date 2023/11/23 20:44
 */
@Slf4j
@RestController
@RequestMapping("user")
public class UserController {

    /**
     * 登录
     *
     * @param user 提交的用户数据，包含用户名和密码
     * @param session httpsession
     * @return 登录结果
     */
    @PostMapping("/login")
    public R login(@RequestBody User user, HttpSession session) {
        ResultMessage resultMessage = new ResultMessage();
        if (user != null && "123".equals(user.getPassword())) {
            resultMessage.setSystemMessage(true);
            session.setAttribute("user", user.getUsername());
            return R.ok()
                .setData(resultMessage);
        } else {
            resultMessage.setSystemMessage(false);
            return R.error("密码错误，登录失败");
        }

    }

    /**
     * 获取用户名
     *
     * @param session httpsession
     * @return 用户名
     */
    @GetMapping("/getUsername")
    public R getUsername(HttpSession session) {
        String user = (String) session.getAttribute("user");
        return R.ok()
            .setData(user);
    }
}
